package cn.jcet.controller.system;

import cn.jcet.config.shiro.ShiroSecurityUtils;
import cn.jcet.dto.DictTypeDto;
import cn.jcet.service.DictTypeService;
import cn.jcet.vo.AjaxResult;
import cn.jcet.vo.DataGridView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * @author 鲜磊
 * @Date 2021/1/25 23:56。
 *  字典类型管理
 */
@RestController
@RequestMapping("/system/dict/type")
public class DictTypeController {

    @Autowired
    private DictTypeService dictTypeService;

    // /system/dict/type/listForPage

    @GetMapping("/listForPage")
    public AjaxResult listForPage(DictTypeDto dictTypeDto){

        DataGridView listPage = dictTypeService.listPage(dictTypeDto);

        return  AjaxResult.success("查询成功",listPage.getData());
    }

    // /system/dict/type/addDictType

    @PostMapping("addDictType")
    public AjaxResult addDictType(@Validated DictTypeDto dictTypeDto){

        // 判断数据库中是否存在id以及类型重复数据
        Boolean dictTypeUnique = this.dictTypeService.checkDictTypeUnique(dictTypeDto.getDictId(), dictTypeDto.getDictType());
        if (dictTypeUnique){
            return AjaxResult.fail("新增字段{"+dictTypeDto.getDictType()+"}失败，字段已存在");
        }

        // 设置当前登录用户人
        dictTypeDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
        // 增加数据
        return AjaxResult.toAjax(this.dictTypeService.insert(dictTypeDto));
    }

    // /system/dict/type/updateDictType
    public AjaxResult updateDictType(@Validated DictTypeDto dictTypeDto){
        Boolean dictTypeUnique = this.dictTypeService.checkDictTypeUnique(dictTypeDto.getDictId(), dictTypeDto.getDictType());
        if (dictTypeUnique){
            return AjaxResult.fail("更新字段{"+dictTypeDto.getDictType()+"}失败，字段已存在");
        }

        // 设置更新人
        dictTypeDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
        // 更新
        return AjaxResult.toAjax(this.dictTypeService.update(dictTypeDto));

    }

    // /system/dict/type/getOne/{dictId}
    @GetMapping("/getOne/{dictId}")
    public AjaxResult getOne(@PathVariable @Validated @NotNull(message = "ID不能为空") Long dictId){

        return AjaxResult.success(this.dictTypeService.selectDictTypeById(dictId));
    }


    // /system/dict/type/deleteDictTypeByIds/{dictIds}

    @DeleteMapping("/deleteDictTypeByIds/{dictIds}")
    public AjaxResult deleteDictTypeByIds(@PathVariable @Validated @NotNull(message = "要删除的ID不能为空") Long[] dictIds){
        // 删除全部数据
        return AjaxResult.toAjax(this.dictTypeService.deleteDictTypeByIds(dictIds));
    }

    // /system/dict/type/selectAllDictType

    @GetMapping("/selectAllDictType")
    public AjaxResult selectAllDictType(){
        // 查询全部数据
        return AjaxResult.success(this.dictTypeService.list().getData());
    }

}
